<template>
  <div class="task-detail-container">
    <n-layout>
      <n-layout-header bordered>
        <div class="header-content">
          <n-button text @click="goBack">
            <n-icon><ArrowBack /></n-icon>
            返回
          </n-button>
          <div class="header-actions">
            <n-button @click="handleDelete">
              删除任务
            </n-button>
            <n-button @click="handleLogout">
              退出
            </n-button>
          </div>
        </div>
      </n-layout-header>
      
      <n-layout-content class="content" v-if="currentTask">
        <!-- 任务基本信息 -->
        <n-card title="任务信息">
          <n-form
            ref="formRef"
            :model="formValue"
            :rules="rules"
          >
            <n-form-item label="任务标题" path="title">
              <n-input v-model:value="formValue.title" />
            </n-form-item>
            <n-form-item label="任务描述" path="description">
              <n-input
                v-model:value="formValue.description"
                type="textarea"
                :autosize="{ minRows: 3, maxRows: 6 }"
              />
            </n-form-item>
            <n-form-item label="所属分组" path="group_id">
              <n-select
                v-model:value="formValue.group_id"
                :options="groupSelectOptions"
              />
            </n-form-item>
            <n-form-item label="截止日期" path="due_date">
              <n-date-picker
                v-model:value="formValue.due_date"
                type="date"
                clearable
              />
            </n-form-item>
            <n-form-item label="状态" path="status">
              <n-select
                v-model:value="formValue.status"
                :options="statusOptions"
              />
            </n-form-item>
            <n-form-item label="重要性">
              <n-checkbox v-model:checked="formValue.is_important">
                标记为重要
              </n-checkbox>
            </n-form-item>
            <n-form-item label="我的一天">
              <n-checkbox v-model:checked="formValue.is_my_day">
                添加到我的一天
              </n-checkbox>
            </n-form-item>
            <n-form-item>
              <n-button type="primary" @click="handleSave" :loading="loading">
                保存更改
              </n-button>
            </n-form-item>
          </n-form>
        </n-card>
        
        <!-- 任务日志 -->
        <n-card title="任务日志" class="logs-card">
          <n-form>
            <n-form-item label="添加日志">
              <n-input
                v-model:value="logContent"
                type="textarea"
                placeholder="请输入日志内容"
              />
            </n-form-item>
            <n-form-item>
              <n-button type="primary" @click="handleAddLog" :loading="loading">
                添加日志
              </n-button>
            </n-form-item>
          </n-form>
          
          <n-list>
            <n-list-item v-for="log in taskLogs" :key="log.log_id">
              <n-thing>
                <template #header>
                  {{ formatDate(log.created_at) }}
                </template>
                <template #description>
                  {{ log.content }}
                </template>
              </n-thing>
            </n-list-item>
          </n-list>
        </n-card>
      </n-layout-content>
      
      <n-layout-content class="content" v-else>
        <n-spin size="large" />
      </n-layout-content>
    </n-layout>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useMessage } from 'naive-ui'
import type { FormInst, FormRules } from 'naive-ui'
import { ArrowBack } from '@vicons/ionicons5'

// 导入所有使用的Naive UI组件
import {
  NLayout,
  NLayoutHeader,
  NLayoutContent,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NDatePicker,
  NCheckbox,
  NCard,
  NList,
  NListItem,
  NThing,
  NSpin,
  NIcon
} from 'naive-ui'

import { useTaskStore } from '../../stores/taskStore'
import { useGroupStore } from '../../stores/groupStore'
import { useUserStore } from '../../stores/userStore'
import type { Task } from '../../types/task'
import type { TaskGroup } from '../../types/group'

const router = useRouter()
const route = useRoute()
const message = useMessage()
const taskStore = useTaskStore()
const groupStore = useGroupStore()
const userStore = useUserStore()

// 状态
const formRef = ref<FormInst | null>(null)
const logContent = ref('')
const loading = ref(false)

// 表单数据
const formValue = ref({
  title: '',
  description: '',
  group_id: null as number | null,
  due_date: null as number | null,
  status: 0,
  is_important: false,
  is_my_day: false
})

// 表单规则
const rules: FormRules = {
  title: {
    required: true,
    message: '请输入任务标题',
    trigger: 'blur'
  },
  group_id: {
    required: true,
    validator: (_rule, value) => {
      if (value === null || value === undefined) {
        return new Error('请选择所属分组');
      }
      // 检查值是否为有效数字
      if (typeof value !== 'number' || isNaN(value) || value <= 0) {
        return new Error('请选择有效的所属分组');
      }
      return true;
    },
    trigger: 'blur'
  }
}

// 计算属性
const currentTask = computed(() => taskStore.getCurrentTask)

const taskLogs = computed(() => taskStore.getTaskLogs)

const groupSelectOptions = computed(() => {
  return groupStore.getAllGroups.map((group: TaskGroup) => ({
    label: group.name,
    value: group.group_id
  }))
})

const statusOptions = [
  { label: '新任务', value: 0 },
  { label: '进行中', value: 1 },
  { label: '已完成', value: 2 }
]

// 方法
const goBack = () => {
  router.back()
}

const handleSave = () => {
  formRef.value?.validate(async (errors) => {
    if (!errors && currentTask.value) {
      try {
        loading.value = true
        // 处理日期格式
        const taskData = {
          ...formValue.value,
          due_date: formValue.value.due_date 
            ? new Date(formValue.value.due_date).toISOString().split('T')[0] 
            : undefined
        }
            
        const result = await taskStore.updateTask(currentTask.value.task_id, taskData)
        if (result.success) {
          message.success('任务更新成功')
              
          // 更新成功后，重新获取任务列表和当前任务详情以确保数据一致性
          await taskStore.fetchTasks()
          // 重新获取当前任务详情
          await taskStore.fetchTaskDetail(currentTask.value.task_id)
        } else {
          message.error(result.message || '任务更新失败')
        }
      } catch (error) {
        message.error('任务更新过程中发生错误')
      } finally {
        loading.value = false
      }
    }
  })
}

const handleDelete = async () => {
  if (currentTask.value) {
    try {
      loading.value = true
      const result = await taskStore.deleteTask(currentTask.value.task_id)
      if (result.success) {
        message.success('任务删除成功')
        
        // 删除成功后，重新获取任务列表以确保数据一致性
        await taskStore.fetchTasks()
        
        router.push('/tasks')
      } else {
        message.error(result.message || '任务删除失败')
      }
    } catch (error) {
      message.error('任务删除过程中发生错误')
    } finally {
      loading.value = false
    }
  }
}

const handleAddLog = async () => {
  if (currentTask.value && logContent.value.trim()) {
    try {
      loading.value = true
      const result = await taskStore.addTaskLog(currentTask.value.task_id, logContent.value)
      if (result.success) {
        message.success('日志添加成功')
        logContent.value = ''
      } else {
        message.error(result.message || '日志添加失败')
      }
    } catch (error) {
      message.error('日志添加过程中发生错误')
    } finally {
      loading.value = false
    }
  }
}

const handleLogout = () => {
  userStore.logout()
  router.push('/login')
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 初始化数据
const initializeData = async () => {
  const taskId = Number(route.params.id)
  if (taskId) {
    // 获取分组列表
    await groupStore.fetchGroups()
    
    // 获取任务日志
    await taskStore.fetchTaskLogs(taskId)
    
    // 强制从服务器获取最新的任务详情，而不是使用缓存
    const taskDetailResult = await taskStore.fetchTaskDetail(taskId)
    
    // 初始化表单数据
    if (taskDetailResult.success && taskDetailResult.data) {
      formValue.value = {
        title: taskDetailResult.data.title,
        description: taskDetailResult.data.description,
        group_id: taskDetailResult.data.group_id,
        due_date: taskDetailResult.data.due_date 
          ? new Date(taskDetailResult.data.due_date).getTime() 
          : null,
        status: taskDetailResult.data.status,
        is_important: taskDetailResult.data.is_important,
        is_my_day: taskDetailResult.data.is_my_day
      }
    }
  }
}

// 监听路由参数变化
watch(
  () => route.params.id,
  (newId, oldId) => {
    if (newId !== oldId) {
      initializeData()
    }
  }
)

// 监听currentTask变化，确保表单数据与store同步
watch(
  () => taskStore.getCurrentTask,
  (newTask) => {
    if (newTask) {
      formValue.value = {
        title: newTask.title,
        description: newTask.description,
        group_id: newTask.group_id,
        due_date: newTask.due_date 
          ? new Date(newTask.due_date).getTime() 
          : null,
        status: newTask.status,
        is_important: newTask.is_important,
        is_my_day: newTask.is_my_day
      }
    }
  },
  { deep: true }
)

// 在组件卸载时清除currentTask，确保下次进入时获取最新数据
onUnmounted(() => {
  taskStore.setCurrentTask(null)
})

// 生命周期
onMounted(initializeData)
</script>

<style scoped>
.task-detail-container {
  height: 100vh;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
}

.content {
  padding: 16px;
}

.logs-card {
  margin-top: 16px;
}
</style>